package BluetoothFileMgr.start;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.widget.Toast;

public class DeviceConnect {

	public static BluetoothDevice device = null;
	private final Context context;
	//private final BluetoothAdapter adapter;
	public static BluetoothSocket mmSocket= null;
	public static DataInputStream din, in;
    //private  BluetoothDevice mmDevice;
	public static String currentDir = null;
	public static Socket wifiSocket;
	InetAddress serveraddress=null;
	
	public void pairDevice(BluetoothDevice device) {
        String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
        Intent intent = new Intent(ACTION_PAIRING_REQUEST);
        String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
        intent.putExtra(EXTRA_DEVICE, device);
        String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT";
        int PAIRING_VARIANT_PIN = 0;
        intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
	
	public void connectToServer()
	{
		Toast toast = Toast.makeText(context, "in connect to SERVER", Toast.LENGTH_SHORT);
        toast.show();
        BluetoothSocket tmp = null;
        //mmDevice = device;
       
        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            BluetoothFileMgrActivity.adap.cancelDiscovery();
        } catch (IOException e) { }
        DeviceConnect.mmSocket = tmp;
        
        try {
			din = new DataInputStream(mmSocket.getInputStream());
			mmSocket.connect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        
		/*Runnable connectThread = new ConnectThread(device, BluetoothFileMgrActivity.adap, context, UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), mmSocket);
		Thread t1 = new Thread(connectThread);
		t1.start();*/
	}
	
	public void connectToWifiServer()
	{
		try {          
			wifiSocket = new Socket(BluetoothFileMgrActivity.serveraddress,1258);
        	//DataOutputStream out=new DataOutputStream(s.getOutputStream());
        	din = new DataInputStream(wifiSocket.getInputStream());
        	
        } catch (Exception e) {
            e.printStackTrace();
            FileManager.tv2.setText("err");
        }
	}
	
	public DeviceConnect(BluetoothDevice device, BluetoothAdapter adapter, Context context)
	{
		this.context = context;
		if(BluetoothFileMgrActivity.mode.equals("Bluetooth"))
		{
			DeviceConnect.device = device;
			connectToServer();
		}
		else
		{
			connectToWifiServer();
		}
			//this.adapter = adapter;
		
		///mmDevice = device;
		
		
	}
	
	public void read()
	{
		String st = null;
		try {
			st = din.readUTF();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
    	if(!st.contains("!!"))
    	{
    		
    	}
    	else
    	{
    		String[] str = new String[10];
    	   	FileManager.dirs.clear();
    	   	FileManager.type.clear();
    	   	FileManager.size.clear();
    	   	str = st.split("!!");
    		currentDir = str[0];
    	   	for(int j = 1; j<str.length; j++)
    		{
    	   		String[] item = new String[10];
    	   		item = str[j].split("!");
    	   		if(item[0].equals("empty"))
    			{
    				
    			}
    			else
    			{
    				FileManager.tv2.setText(str[0]);
    				FileManager.dirs.add(item[1]);
    				FileManager.type.add(item[0]);
    				FileManager.size.add(Long.parseLong(item[2]));
    			}
    			FileManager.adapter2.notifyDataSetChanged();
    		}
    	}
	}
	
	public void trial(String filename, long size) //throws Exception
    {
    	File newFile = null;
    	FileInputStream fin = null;
    	try {
    		//tv.setText("before");
    		newFile = new File(Environment.getExternalStorageDirectory().toString()+"/"+filename);
    		newFile.createNewFile();
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
    		//tv.setText(e.toString());
    		e.printStackTrace();
    	}
  		
    		DataOutputStream dout = null;
    		FileOutputStream fout = null;
    		try {
    			fout = new FileOutputStream(newFile);
    			dout = new DataOutputStream(fout);
    			//fout.close();
    			
    		} catch (FileNotFoundException e) { } 	                   	
    		String st = null;
    		byte b[] = new byte[1000];
    		byte by;// = new byte();
    		//FileManager.tv2.setText("before readUTF");
    		try { 			
    			long i = 1;//pdf=246000
    			while(i<=size)
    			{
    				//tv.setText(""+i);
    				b = new byte[1000];
    				din.read(b, 0, 1);
    				by = b[0];
    				dout.write(by);
    				//System.out.print(by);
    				i++;
    			}
    			toastMessage("FILE RECIEVED", Toast.LENGTH_LONG);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			//tv.setText("catch of inst.read");
    		}
    	
    		try{
    			fout.close();
    			dout.close();
    		} catch (Exception e) { }	
    }	

	public void toastMessage(CharSequence text, int duration)
    {
    	Context context = BluetoothFileMgrActivity.mainContext;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
	
}


